package com.link.play.fit.ai.ui.setting

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.ActivityResult
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.aigestudio.wheelpicker.WheelPicker.OnWheelChangeListener
import com.google.firebase.firestore.Filter
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.viewBind
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.AcSetWeightBinding
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import com.link.play.fit.ai.utils.EventUtils
import com.link.play.fit.ai.utils.HealthUtils.convertKgToLbs
import com.link.play.fit.ai.utils.HealthUtils.convertLbsToKg
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Create by SleepDog on 2025-04-02
 * 记录设置体重
 */
class SetWeightAc : BaseActivity<AcSetWeightBinding>(AcSetWeightBinding::inflate) {
    private var mCurrentLb = 0
    private var mCurrentKg = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            viewBind {
                ivBack.setOnClickListener {
                    finish()
                }
                tvSave.setThrottleListener {
                    val isMetric = switchButton.isChecked
                    if (isMetric) mCurrentLb = convertKgToLbs(mCurrentKg)
                    else mCurrentKg = convertLbsToKg(mCurrentLb)
                    CloudStore.addToList(
                        DOC_LOG_WEIGHT,
                        DOC_LOG_WEIGHT,
                        getDayOfMonth(),
                        LogWeightBean(mCurrentKg, mCurrentLb)
                    )
                    GlobalConfig.imperialMetric = isMetric
                    EventUtils.event("log_weight")
                    lifecycleScope.launch {

                        val data: UserGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE) ?: UserGuide()

                        data.weightKg = mCurrentKg
                        data.weightLbs = mCurrentLb
                        data.imperialMetric = isMetric
                        CloudStore.set(DOC_USER_GUIDE, data)

                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                }
                val lbData = async(Dispatchers.Default) {
                    val list = mutableListOf<String>()
                    var start = 40 - 1
                    repeat(800 - start) {
                        start++
                        list.add("$start lb")
                    }
                    list.toList()
                }.await()
                val kgData = async(Dispatchers.Default) {
                    val list = mutableListOf<String>()
                    var start = 20 - 1
                    repeat(360 - start) {
                        start++
                        list.add("$start kg")
                    }
                    list.toList()
                }.await()
                lbWheelPicker.data = lbData
                kgWheelPicker.data = kgData

                if (GlobalConfig.imperialMetric) {
                    switchButton.isChecked = true
                    lbWheelLayout.isVisible = false
                    kgWheelLayout.isVisible = true
                    ImperialText.setTextColor(getColor(R.color.color_69))
                    MetricText.setTextColor(getColor(R.color.black_11))
                } else {
                    switchButton.isChecked = false
                    lbWheelLayout.isVisible = true
                    kgWheelLayout.isVisible = false
                    MetricText.setTextColor(getColor(R.color.color_69))
                    ImperialText.setTextColor(getColor(R.color.black_11))
                }

                switchButton.setOnCheckedChangeListener { _, isChecked ->
                    if (isChecked) {
                        lbWheelLayout.isVisible = false
                        kgWheelLayout.isVisible = true
                        ImperialText.setTextColor(getColor(R.color.color_69))
                        MetricText.setTextColor(getColor(R.color.black_11))
                        mCurrentKg = convertLbsToKg(mCurrentLb)
                        kgWheelPicker.setSelectedItemPosition(
                            kgData.indexOf("$mCurrentKg kg"),
                            false
                        )
                    } else {
                        lbWheelLayout.isVisible = true
                        kgWheelLayout.isVisible = false
                        mCurrentLb = convertKgToLbs(mCurrentKg)
                        lbWheelPicker.setSelectedItemPosition(
                            lbData.indexOf("$mCurrentLb lb"),
                            false
                        )
                        MetricText.setTextColor(getColor(R.color.color_69))
                        ImperialText.setTextColor(getColor(R.color.black_11))
                    }
                }

                kgWheelPicker.setOnWheelChangeListener(object : OnWheelChangeListener {
                    override fun onWheelScrolled(offset: Int) = Unit
                    override fun onWheelScrollStateChanged(state: Int) = Unit
                    override fun onWheelSelected(position: Int) {
                        runCatching {
                            val kgValue = kgData[position].split(" ")[0].toInt()
                            mCurrentKg = kgValue
                        }
                    }
                })
                lbWheelPicker.setOnWheelChangeListener(object : OnWheelChangeListener {
                    override fun onWheelScrolled(offset: Int) = Unit
                    override fun onWheelScrollStateChanged(state: Int) = Unit
                    override fun onWheelSelected(position: Int) {
                        runCatching {
                            val lbValue = lbData[position].split(" ")[0].toInt()
                            mCurrentLb = lbValue
                        }
                    }
                })
                lifecycleScope.launch(Dispatchers.Default) {
                    val logWeightBean = CloudStore.getListItem<LogWeightBean>(
                        DOC_LOG_WEIGHT,
                        DOC_LOG_WEIGHT,
                        Filter.lessThanOrEqualTo("createTime", System.currentTimeMillis())
                    )
                    if (GlobalConfig.imperialMetric) {
                        val index = kgData.indexOf("${logWeightBean?.weightKg} kg")
                        mCurrentKg = kgData[if (index >= 0) index else 0].split(" ")[0].toInt()
                        withContext(Dispatchers.Main) {
                            kgWheelPicker.setSelectedItemPosition(
                                index, false
                            )
                        }
                    } else {
                        val index = lbData.indexOf("${logWeightBean?.weightLbs} lb")
                        mCurrentLb = lbData[if (index >= 0) index else 0].split(" ")[0].toInt()
                        withContext(Dispatchers.Main) {
                            lbWheelPicker.setSelectedItemPosition(
                                index, false
                            )
                        }
                    }
                }
            }


        }


    }
}